import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { excelColumns } from '@/common/constants/system/resource'
import { formatWhere } from '@/common/utils/sql'
import commonExport from '@/api/v1/common/file/export'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/role`,
})
router.post(
  '/export',
  verifyToken,
  commonExport({
    async getResult(ctx: Models.Ctx) {
      const { roleName, status = '1', ids } = ctx.request.body as any
      let where = ''
      if (ids?.length) {
        // 根据ids查询数据
        where = `WHERE 1=1 AND id IN (${ids.map((item: string | number) => `'${item}'`).join()})`
      } else {
        // 根据查询条件查询数据
        where = `WHERE 1=1 ${roleName ? `AND role_name LIKE '%${roleName}%'` : ``}`
      }
      where += ` AND status = '${status}'`
      where = formatWhere(where)
      return (await command(`SELECT role_code, role_name FROM system_role ${where}`, true)).results
    },
    fileName: '权限列表',
    excelColumns,
  }),
)
export default router
